package cc.iteachyou.cms.controller.tools;

import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cc.iteachyou.cms.common.ResponseResult;
import cc.iteachyou.cms.common.StateCodeEnum;
import cn.hutool.core.util.StrUtil;

/**
 * Html工具类
 * @author Jonas
 *
 */
@RestController
@RequestMapping("tools/html")
public class HtmlToolController {
	
	/**
	 * 格式化Json
	 * @param params
	 * @return
	 */
	@PostMapping("format")
	public ResponseResult format(@RequestBody Map<String,String> params) {
		ResponseResult result = null;
		if(!params.containsKey("html") || StrUtil.isBlank(params.get("html"))) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
		try {
			Document document = Jsoup.parse(params.get("html"));
			String html = document.html();
			result = ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), html, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		} catch (Exception e) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
	}
	
	/**
	 * 压缩Json
	 * @param params
	 * @return
	 */
	@PostMapping("compress")
	public ResponseResult compress(@RequestBody Map<String,String> params) {
		ResponseResult result = null;
		if(!params.containsKey("json") || StrUtil.isBlank(params.get("json"))) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
		try {
			JSONObject jsonObject = JSONObject.parseObject(params.get("json"));
			String jsonString = JSONObject.toJSONString(jsonObject);
			result = ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), jsonString, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		} catch (Exception e) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
	}
	
}
